package health_system.health_system.service;

import health_system.health_system.entity.User;
import health_system.health_system.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

/**
 * Service for security-related utilities and checks
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SecurityService {

    private final UserRepository userRepository;
    
    /**
     * Check if the current authenticated user is the user with the given ID
     * 
     * @param userId the user ID to check
     * @return true if the current user has the given ID, false otherwise
     */
    public boolean isCurrentUser(Long userId) {
        Long currentUserId = getCurrentUserId();
        return currentUserId != null && currentUserId.equals(userId);
    }
    
    /**
     * Get the currently authenticated user's ID
     * 
     * @return the current user's ID, or null if not authenticated
     */
    public Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return null;
        }
        
        String username = authentication.getName();
        User currentUser = userRepository.findByUsername(username)
                .orElse(null);
                
        return currentUser != null ? currentUser.getId() : null;
    }
    
    /**
     * Get the currently authenticated username
     * 
     * @return the current username, or null if not authenticated
     */
    public String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return null;
        }
        
        return authentication.getName();
    }
} 